﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using USERS.CYT369.COM.Models;

namespace USERS.CYT369.COM.Controllers
{
    //上传文章图片
    public partial class BrandController
    {
        private static Newtonsoft.Json.Linq.JObject m_FileConfiguration { get; set; }

        public BrandController()
        {
            var config = System.IO.File.ReadAllText(this.BrandFileConfig);

            

            m_FileConfiguration = Newtonsoft.Json.JsonConvert.DeserializeObject(config) as Newtonsoft.Json.Linq.JObject;
        }

        private string BrandFileConfig
        {
            get
            {
                string path = string.Empty;
                var dir = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).Directory;

                do
                {
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(dir.FullName, "wwwroot")))
                    {
                        path = System.IO.Path.Combine(dir.FullName, @"wwwroot\js\brand\brand-file-config.json");
                        break;
                    }
                    dir = dir.Parent;
                } while (dir != null);

                return path;
            }
        }

        public ActionResult Controller()
        {
            string action = Request.Query.GetString("action");
            if (!string.IsNullOrEmpty(action))
            {
                switch (action)
                {
                    case "config":
                        return Config();

                    case "uploadimage":
                        return UploadImage();

                    case "uploadscrawl":
                        return UploadScrawl();

                    case "uploadvideo":
                        return UploadVideo();

                    case "uploadfile":
                        return UploadFile();

                    case "listimage":
                        //return ListImage();
                        return null;

                    case "listfile":
                        //return ListFile();
                        return null;

                    case "catchimage":
                        return CatchImage();
                }
            }

            return DefaultJson(new
            {
                state = "请求地址出错"
            });
        }

        public ActionResult Config()
        {
            var config = System.IO.File.ReadAllText(this.BrandFileConfig);

            return Content(config);
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImage()
        {
            var retVal = new ExecuteResult();
            int brandId = Request.Form.GetInteger("BrandID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);
            if (brandId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("imagePathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("imageMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("imageAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };

                var docFile = DoSaveFile(Request.Form.Files[0], config, userId, brandId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public ActionResult UploadScrawl()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);

            if (docId > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("scrawlPathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("scrawlMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("scrawlAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    }),
                    oriName = "scrawl.png"
                };

                var file = new Base64File(this.Request, m_FileConfiguration.GetString("scrawlFieldName"));
                file.Name = config.oriName;

                var docFile = DoSaveFile(file, config, userId, (int)docId, "base64");
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }


        [HttpPost]
        public ActionResult UploadVideo()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);

            if (docId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("videoPathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("videoMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("videoAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };

                var docFile = DoSaveFile(Request.Form.Files[0], config, userId, (int)docId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }


        [HttpPost]
        public ActionResult UploadFile()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);

            if (docId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("filePathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("fileMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("fileAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };


                var docFile = DoSaveFile(Request.Form.Files[0], config, userId, (int)docId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        //[HttpPost]
        //public ActionResult ListImage()
        //{
        //    var config = new News.CYT369.Com.Models.UploadFileConfig()
        //    {
        //        Path = this.Configuration.GetString("imageManagerListPath"),
        //        ListSize = this.Configuration.GetInteger("imageManagerListSize"),
        //        AllowFiles = this.Configuration.GetArray<string>("imageManagerAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
        //        {
        //            var tv = tk as Newtonsoft.Json.Linq.JValue;
        //            if (tv != null && tv.Value != null)
        //            {
        //                return tv.Value.ToString();
        //            }

        //            return null;
        //        })
        //    };

        //    var page = Request.Query.GetInteger("start", 0);
        //    var size = Request.Query.GetInteger("size", config.ListSize.HasValue ? config.ListSize.Value : 20);
        //    int total = 0;

        //    var list = WebApp.Models.OssClientService.ListFiles(System.IO.Path.Combine(WebApp.Models.Common.SystemSettingService.Instance.FileDir, config.Path), page, size, ref total, new string[] { "*.jpg", "*.jepg", "*.png", "*.gif", "*.bmp" });
        //    var listImage = new List<object>();
        //    if (list != null)
        //    {
        //        foreach (var key in list)
        //        {
        //            var keyFile = key.FullName.Replace(WebApp.Models.Common.SystemSettingService.Instance.FileDir, "").Replace("\\", "/");
        //            listImage.Add(new
        //            {
        //                url = string.Format("{0}/{1}", WebApp.Models.Common.SystemSettingService.Instance.BaseURL, keyFile.Substring(1, keyFile.Length - 1)),
        //                mtime = key.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")
        //            });
        //        }
        //    }

        //    return DefaultJson(new
        //    {
        //        state = total > 0 ? "SUCCESS" : "no match file",
        //        list = listImage,
        //        start = page,
        //        total = total
        //    });
        //}

        //[HttpPost]
        //public ActionResult ListFile()
        //{
        //    var config = new News.CYT369.Com.Models.UploadFileConfig()
        //    {
        //        Path = this.Configuration.GetString("fileManagerListPath"),
        //        ListSize = this.Configuration.GetInteger("fileManagerListSize"),
        //        AllowFiles = this.Configuration.GetArray<string>("fileManagerAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
        //        {
        //            var tv = tk as Newtonsoft.Json.Linq.JValue;
        //            if (tv != null && tv.Value != null)
        //            {
        //                return tv.Value.ToString();
        //            }

        //            return null;
        //        })
        //    };


        //    var page = Request.Query.GetInteger("start", 0);
        //    var size = Request.Query.GetInteger("size", config.ListSize.HasValue ? config.ListSize.Value : 20);
        //    int total = 0;

        //    var list = News.CYT369.Com.Service.OssClientService.Instance.ListFiles(News.CYT369.Com.Domains.SystemSettingService.Instance.InternalBucket, "", page, size, ref total);
        //    var listImage = new List<object>();
        //    if (list != null)
        //    {
        //        foreach (var key in list)
        //        {
        //            var keyFile = key.FullName.Replace(WebApp.Models.Common.SystemSettingService.Instance.FileDir, "").Replace("\\", "/");

        //            listImage.Add(new
        //            {
        //                url = string.Format("{0}/{1}", News.CYT369.Com.Domains.SystemSettingService.Instance.InternalBucket.HttpURL, keyFile.Substring(1, keyFile.Length - 1)),
        //                mtime = key.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")
        //            });
        //        }
        //    }

        //    return DefaultJson(new
        //    {
        //        state = total > 0 ? "SUCCESS" : "no match file",
        //        list = listImage,
        //        start = page,
        //        total = total
        //    });
        //}

        [HttpPost]
        public ActionResult CatchImage()
        {

            return Content("");
        }

        public USERS.CYT369.COM.MODELS.Brand.BrandImage DoSaveFile(Microsoft.AspNetCore.Http.IFormFile file, UploadFileConfig config, int userId, int brandId, string type = "upload")
        {
            var now = DateTime.Now;
            string key = string.Format(config.PathFormat, userId, now.Year, now.Month, now.Day, brandId, now.Ticks);

            switch (type)
            {
                case "remote":
                    break;

                case "base64":
                    {
                        var fileInfo = new System.IO.FileInfo(file.FileName);
                        if (CheckFile(config, fileInfo.Extension, file.Length))
                        {
                            key += fileInfo.Extension;
                        }

                        using (var stream = file.OpenReadStream())
                        {
                            if (USERS.CYT369.COM.UTILITY.OssClientService.Instance.SaveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.BrandInternalBucket, key, stream))
                            {
                                var brandFile = new USERS.CYT369.COM.MODELS.Brand.BrandImage()
                                {
                                    BrandID = brandId,
                                    FileExtension = fileInfo.Extension,
                                    Name = fileInfo.Name,
                                    ImagePath = key,
                                };
                                if (brandFile.Name != null && brandFile.Name.Length > 128)
                                {
                                    brandFile.Name = brandFile.Name.Substring(brandFile.Name.Length - 128, 128);
                                }
                                if (USERS.CYT369.COM.DAL.BrandService.Instance.SaveBrandImage(brandFile))
                                {
                                    return brandFile;
                                }
                            }
                        }
                    }
                    break;

                default:
                    {
                        var fileInfo = new System.IO.FileInfo(file.FileName);
                        if (CheckFile(config, fileInfo.Extension, file.Length))
                        {
                            key += fileInfo.Extension;
                        }

                        using (var stream = file.OpenReadStream())
                        {
                            if (USERS.CYT369.COM.UTILITY.OssClientService.Instance.SaveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.BrandInternalBucket, key, stream))
                            {
                                var brandFile = new USERS.CYT369.COM.MODELS.Brand.BrandImage()
                                {
                                    BrandID = brandId,
                                    FileExtension = fileInfo.Extension,
                                    Name = fileInfo.Name,
                                    ImagePath = key,
                                };
                                if (brandFile.Name != null && brandFile.Name.Length > 128)
                                {
                                    brandFile.Name = brandFile.Name.Substring(brandFile.Name.Length - 128, 128);
                                }

                                if (USERS.CYT369.COM.DAL.BrandService.Instance.SaveBrandImage(brandFile))
                                {
                                    brandFile.ImagePath = string.Format("{0}/{1}", USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.BrandInternalBucket.HttpURL, key);
                                    return brandFile;
                                }
                            }
                        }
                    }
                    break;
            }

            return null;
        }

        private bool CheckFile(UploadFileConfig config, string extension, long fileLength)
        {
            if (config.MaxSize.HasValue && fileLength > config.MaxSize)
            {
                throw new Exception("文件大小超出限制");
            }

            if (config.AllowFiles != null && string.IsNullOrEmpty(extension) == false)
            {
                if (!config.AllowFiles.Contains(extension.ToLower()))
                {
                    throw new Exception("文件类型不允许");
                }
            }

            return true;
        }



    }
}
